'''
Created on Aug 31, 2011

@author: bstar
'''
from zope.interface import implements
from twisted.internet.interfaces import IPullProducer
from twisted.internet.defer import Deferred


class FileChunkProducer(object):
    implements(IPullProducer)
    chunk = 1024
    _closed = False
    def __init__(self, consumer, filepath):
        self.consumer = consumer
        self.filepath = filepath
        self.file= open(filepath)
        self.position = 0
        self.defer = Deferred()
    def getDeferred(self):
        return self.defer
    def resumeProducing(self):
        if self._closed == True:
            return
        self.position += self.chunk
        data = self.file.read(self.chunk)
        self.consumer.write(data)
        #logger.debug("Send chunk %s for file %s"%(self.position, self.filepath))   
        if len(data) < 1:
            self.stopProducing()
            return None
        return True
        #    self.defer.callback(True)
        

    def stopProducing(self):
        print "STOP PRODUCING"
        self._closed = True
        self.file.close()
        self.defer.callback(True)